package cn.edu.hqu.cst.android.xzy.xzy;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnBindService,btnUnbindService,btnGetStatus;
    TextView tvServiceStatus;
    MyService01.MyServiceBinder serviceBinder;
    boolean isServiceBind=false;

    ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回 Service 的 Binder 对象
            System.out.println("--Service Connected--");
            serviceBinder = (MyService01.MyServiceBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("--Service Disconnected--");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBindService=findViewById(R.id.btn_main_activity_bind_service);
        btnUnbindService=findViewById(R.id.btn_main_activity_unbind_service);
        btnGetStatus=findViewById(R.id.btn_main_activity_get_status);
        tvServiceStatus=findViewById(R.id.tv_main_activity_service_status);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, MyService01.class);
        switch (v.getId()) {
            case R.id.btn_main_activity_bind_service:
                //如果 service 尚未绑定就绑定，如果已经绑定则忽略
                bindService(intent,conn,Service.BIND_AUTO_CREATE);
                break;
            case R.id.btn_main_activity_get_status:
                //如果 service 已经绑定，获取 service 的 count 计数并显示在截面上。
                Toast.makeText(MainActivity.this,"Service的值为:"+serviceBinder.getCount(),Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_main_activity_unbind_service:
                //如果 service 已经绑定，则可以解绑，否则忽略
                unbindService(conn);
                break;
        }
    }
}
